import 'dart:io';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'flutter_pangle_platform_interface.dart';
import 'flutter_pangle_method_channel.dart' as channel;
export 'flutter_pangle_platform_interface.dart';

/// Flutter Pangle SDK 主类
class FlutterPangle {
  // 确保默认实现已注册
  static final _ensureInit = channel.MethodChannelFlutterPangle();

  FlutterPangle() {
    // 触发静态字段的懒加载，确保默认实现完成注册
    // ignore: unnecessary_statements
    FlutterPangle._ensureInit;
  }

  /// 初始化SDK
  ///
  /// [config] SDK配置信息
  /// 返回初始化是否成功
  Future<bool> initializeSDK(PAGSSDKConfig config) {
    return FlutterPanglePlatform.instance.initializeSDK(config);
  }

  /// 设置合规设置
  ///
  /// [eligible] true表示用户适合观看短剧内容，false表示不适合
  Future<void> setEligibleAudience(bool eligible) {
    return FlutterPanglePlatform.instance.setEligibleAudience(eligible);
  }

  /// 设置内容语言（单个）
  ///
  /// [language] 语言代码，如 'zh_hans', 'en', 'vi' 等
  Future<void> setContentLanguage(String language) {
    return FlutterPanglePlatform.instance.setContentLanguage(language);
  }

  /// 设置内容语言（多个）
  ///
  /// [languages] 语言代码列表
  Future<void> setContentLanguages(List<String> languages) {
    return FlutterPanglePlatform.instance.setContentLanguages(languages);
  }

  /// 获取默认短剧列表
  ///
  /// [index] 页索引，从1开始
  /// [count] 请求数量
  Future<PAGSFeedListResponse> requestFeedList({
    required int index,
    required int count,
  }) {
    return FlutterPanglePlatform.instance.requestFeedList(
      index: index,
      count: count,
    );
  }

  /// 获取指定分类或短剧的列表
  ///
  /// [index] 页索引，从1开始
  /// [count] 请求数量
  /// [categoryIds] 分类ID集合，可选
  /// [shortplayIds] 短剧ID集合，可选
  Future<PAGSFeedListResponse> requestFeedListWithFilters({
    required int index,
    required int count,
    List<int>? categoryIds,
    List<int>? shortplayIds,
  }) {
    return FlutterPanglePlatform.instance.requestFeedListWithFilters(
      index: index,
      count: count,
      categoryIds: categoryIds,
      shortplayIds: shortplayIds,
    );
  }

  /// 获取热门短剧列表
  ///
  /// [index] 页索引，从1开始
  /// [count] 请求数量
  Future<PAGSFeedListResponse> requestPopularDrama({
    required int index,
    required int count,
  }) {
    return FlutterPanglePlatform.instance.requestPopularDrama(
      index: index,
      count: count,
    );
  }

  /// 获取新剧列表
  ///
  /// [index] 页索引，从1开始
  /// [count] 请求数量
  Future<PAGSFeedListResponse> requestNewFeedList({
    required int index,
    required int count,
  }) {
    return FlutterPanglePlatform.instance.requestNewFeedList(
      index: index,
      count: count,
    );
  }

  /// 获取指定标签的列表
  ///
  /// [tag] 标签值，如 4 表示近期收藏最多的短剧
  /// [index] 页索引，从1开始
  /// [count] 请求数量
  Future<PAGSFeedListResponse> requestDramaWithTag({
    required int tag,
    required int index,
    required int count,
  }) {
    return FlutterPanglePlatform.instance.requestDramaWithTag(
      tag: tag,
      index: index,
      count: count,
    );
  }

  /// 获取短剧分类列表
  ///
  /// [language] 语种，如 'zh_hans', 'en' 等
  Future<List<PAGSCategoryItem>> getCategoryList(String language) {
    return FlutterPanglePlatform.instance.getCategoryList(language);
  }

  /// 搜索短剧
  ///
  /// [index] 页索引，从1开始
  /// [count] 请求数量
  /// [keyword] 搜索关键词
  /// [isFuzzy] 是否模糊搜索
  Future<PAGSFeedListResponse> requestSearchDrama({
    required int index,
    required int count,
    required String keyword,
    required bool isFuzzy,
  }) {
    return FlutterPanglePlatform.instance.requestSearchDrama(
      index: index,
      count: count,
      keyword: keyword,
      isFuzzy: isFuzzy,
    );
  }

  /// 检查当前地区是否支持播放
  ///
  /// 返回 1=支持, 2=不支持, 0=未知
  Future<int> checkPlayStatus() {
    return FlutterPanglePlatform.instance.checkPlayStatus();
  }

  /// 设置收藏状态
  ///
  /// [collected] true表示收藏，false表示取消收藏
  /// [shortplayId] 短剧ID
  Future<bool> setCollected({
    required bool collected,
    required int shortplayId,
  }) {
    return FlutterPanglePlatform.instance.setCollected(
      collected: collected,
      shortplayId: shortplayId,
    );
  }

  /// 清除本地缓存
  Future<void> clearLocalCache() {
    return FlutterPanglePlatform.instance.clearLocalCache();
  }

  /// 获取设备当前语言
  String getCurrentLanguage() {
    return FlutterPanglePlatform.instance.getCurrentLanguage();
  }

  /// 预热播放器引擎
  /// 在应用启动时调用，可以提前初始化播放器引擎，减少首次播放时的卡顿
  /// 这是一个可选操作，即使失败也不会影响正常使用
  Future<void> warmUpPlayerEngine() {
    return FlutterPanglePlatform.instance.warmUpPlayerEngine();
  }
}

/// Android 端播放页（使用原生 Fragment 承载）
/// 需要传入 SDK ShortPlay 的 JSON（可由 Android 端返回或按官方字段构建）
class PangleDetailAndroidView extends StatefulWidget {
  final String shortplayJson;

  /// 控制器：承载播放配置与事件回调，并提供控制方法
  final PangleDetailController controller;

  const PangleDetailAndroidView({
    super.key,
    required this.shortplayJson,
    required this.controller,
  });

  @override
  State<PangleDetailAndroidView> createState() =>
      _PangleDetailAndroidViewState();
}

class _PangleDetailAndroidViewState extends State<PangleDetailAndroidView> {
  StreamSubscription? _sub;
  MethodChannel? _method;
  int? _pendingSeekSeconds;
  int? _pendingStartIndex;
  bool? _pendingSetCurrent;
  bool _pendingPlayRequest = false;
  bool _pendingPauseRequest = false;

  void _onPlatformViewCreated(int id) {
    debugPrint(
      '[PangleDetailView] onPlatformViewCreated id=$id autoPlay=${widget.controller.autoPlay}',
    );
    final channel = EventChannel(
      'flutter_pangle/detail_fragment_events_' + id.toString(),
    );
    _method = MethodChannel(
      'flutter_pangle/detail_fragment_methods_' + id.toString(),
    );
    widget.controller._attach(
      _seekToSeconds,
      _pause,
      _play,
      _setSpeed,
      _startPlayIndex,
      _setCurrentFragment,
    );
    _sub?.cancel();
    _sub = channel.receiveBroadcastStream().listen((dynamic message) {
      if (message is Map) {
        final map = Map<String, dynamic>.from(
          message.map((k, v) => MapEntry(k.toString(), v)),
        );
        final event = (map['event'] ?? '').toString();
        final data = Map<String, dynamic>.from(
          (map['data'] as Map?)?.map((k, v) => MapEntry(k.toString(), v)) ?? {},
        );
        debugPrint('[PangleDetailView] id=$id event=$event');
        widget.controller.onEvent?.call(event, data);
      }
    });
    _flushPending();
    if (widget.controller.autoPlay) {
      debugPrint('[PangleDetailView] autoPlay start for id=$id');
      _setCurrentFragment(true);
      _play();
    }
  }

  Future<void> _seekToSeconds(int seconds) async {
    final m = _method;
    if (m == null) {
      _pendingSeekSeconds = seconds;
      debugPrint('[PangleDetailView] pending seekToSeconds=$seconds');
      return;
    }
    try {
      await m.invokeMethod('seekToSeconds', {'seconds': seconds});
      _pendingSeekSeconds = null;
    } catch (_) {}
  }

  Future<void> _pause() async {
    final m = _method;
    if (m == null) {
      _pendingPauseRequest = true;
      _pendingPlayRequest = false;
      debugPrint('[PangleDetailView] pending pause');
      return;
    }
    try {
      await m.invokeMethod('pausePlay');
      _pendingPauseRequest = false;
    } catch (_) {}
  }

  Future<void> _play() async {
    final m = _method;
    if (m == null) {
      _pendingPlayRequest = true;
      _pendingPauseRequest = false;
      debugPrint('[PangleDetailView] pending play');
      return;
    }
    try {
      await m.invokeMethod('startPlay');
      _pendingPlayRequest = false;
    } catch (_) {}
  }

  Future<void> _setSpeed(double speed) async {
    final m = _method;
    if (m == null) return;
    try {
      await m.invokeMethod('setVideoSpeed', {'speed': speed});
    } catch (_) {}
  }

  Future<void> _startPlayIndex(int index) async {
    final m = _method;
    if (m == null) {
      _pendingStartIndex = index;
      debugPrint('[PangleDetailView] pending startPlayIndex=$index');
      return;
    }
    try {
      await m.invokeMethod('startPlayIndex', {'index': index});
      _pendingStartIndex = null;
    } catch (_) {}
  }

  Future<void> _setCurrentFragment(bool isCurrent) async {
    final m = _method;
    if (m == null) {
      _pendingSetCurrent = isCurrent;
      debugPrint('[PangleDetailView] pending setCurrentFragment=$isCurrent');
      return;
    }
    try {
      await m.invokeMethod('setCurrentFragment', {'isCurrent': isCurrent});
      _pendingSetCurrent = null;
    } catch (_) {}
  }

  @override
  void dispose() {
    _sub?.cancel();
    widget.controller._attach(null, null, null, null, null, null);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid) {
      return AndroidView(
        viewType: 'flutter_pangle/detail_fragment',
        layoutDirection: TextDirection.ltr,
        creationParams: {
          'shortplay_json': widget.shortplayJson,
          'play_single_item': widget.controller.playSingleItem,
          'initial_play_index': widget.controller.initialPlayIndex,
          'auto_play': widget.controller.autoPlay,
        },
        creationParamsCodec: const StandardMessageCodec(),
        onPlatformViewCreated: _onPlatformViewCreated,
      );
    } else if (Platform.isIOS) {
      return UiKitView(
        viewType: 'flutter_pangle/detail_fragment',
        layoutDirection: TextDirection.ltr,
        creationParams: {
          'shortplay_json': widget.shortplayJson,
          'play_single_item': widget.controller.playSingleItem,
          'initial_play_index': widget.controller.initialPlayIndex,
          'auto_play': widget.controller.autoPlay,
        },
        creationParamsCodec: const StandardMessageCodec(),
        onPlatformViewCreated: _onPlatformViewCreated,
      );
    } else {
      return const SizedBox.shrink();
    }
  }

  Future<void> _flushPending() async {
    final m = _method;
    if (m == null) return;
    if (_pendingSetCurrent != null) {
      final value = _pendingSetCurrent!;
      _pendingSetCurrent = null;
      debugPrint('[PangleDetailView] flush setCurrentFragment=$value');
      try {
        await m.invokeMethod('setCurrentFragment', {'isCurrent': value});
      } catch (_) {}
    }
    if (_pendingStartIndex != null) {
      final value = _pendingStartIndex!;
      _pendingStartIndex = null;
      debugPrint('[PangleDetailView] flush startPlayIndex=$value');
      try {
        await m.invokeMethod('startPlayIndex', {'index': value});
      } catch (_) {}
    }
    if (_pendingSeekSeconds != null) {
      final value = _pendingSeekSeconds!;
      _pendingSeekSeconds = null;
      debugPrint('[PangleDetailView] flush seekToSeconds=$value');
      try {
        await m.invokeMethod('seekToSeconds', {'seconds': value});
      } catch (_) {}
    }
    if (_pendingPauseRequest) {
      _pendingPauseRequest = false;
      debugPrint('[PangleDetailView] flush pause');
      try {
        await m.invokeMethod('pausePlay');
      } catch (_) {}
    } else if (_pendingPlayRequest) {
      _pendingPlayRequest = false;
      debugPrint('[PangleDetailView] flush play');
      try {
        await m.invokeMethod('startPlay');
      } catch (_) {}
    }
  }
}

/// 控制器：用于控制原生播放页（例如跳转进度）
class PangleDetailController {
  /// 是否只播放单个视频（不允许左右/上下切换），对应原生 `builder.playSingleItem(...)`
  bool playSingleItem;

  /// 初始播放的剧集索引（默认 1），对应原生 `builder.startPlayIndex(...)`
  int initialPlayIndex;

  /// 是否自动播放（默认 false），为 true 时加载后自动播放
  bool autoPlay;

  /// 接收原生事件：event 为事件名，data 为事件数据
  void Function(String event, Map<String, dynamic> data)? onEvent;

  void Function(int seconds)? _seek;
  Future<void> Function()? _pause;
  Future<void> Function()? _play;
  Future<void> Function(double speed)? _setSpeed;
  Future<void> Function(int index)? _startIdx;
  Future<void> Function(bool isCurrent)? _setCurrentFrag;

  PangleDetailController({
    this.playSingleItem = true,
    this.initialPlayIndex = 1,
    this.autoPlay = false,
    this.onEvent,
  });
  void _attach(
    void Function(int seconds)? seek,
    Future<void> Function()? pause,
    Future<void> Function()? play,
    Future<void> Function(double speed)? setSpeed,
    Future<void> Function(int index)? startIdx,
    Future<void> Function(bool isCurrent)? setCurrentFrag,
  ) {
    _seek = seek;
    _pause = pause;
    _play = play;
    _setSpeed = setSpeed;
    _startIdx = startIdx;
    _setCurrentFrag = setCurrentFrag;
  }

  /// 跳转到指定秒数
  Future<void> seekToSeconds(int seconds) async {
    final f = _seek;
    if (f == null) return;
    f(seconds);
  }

  Future<void> pause() async {
    final f = _pause;
    if (f != null) await f();
  }

  Future<void> play() async {
    final f = _play;
    if (f != null) await f();
  }

  Future<void> setSpeed(double speed) async {
    final f = _setSpeed;
    if (f != null) await f(speed);
  }

  /// 从指定索引开始播放
  Future<void> startPlayIndex(int index) async {
    final f = _startIdx;
    if (f != null) await f(index);
  }

  /// 设置当前Fragment状态（iOS端用于PageView场景）
  Future<void> setCurrentFragment(bool isCurrent) async {
    final f = _setCurrentFrag;
    if (f != null) await f(isCurrent);
  }
}
